package com.fantuan.db.service.impl;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.fantuan.db.bean.ConsumeLog;
import com.fantuan.db.bean.FundLog;
import com.fantuan.db.bean.Group;
import com.fantuan.db.bean.User;
import com.fantuan.db.bean.UserMoney;
import com.fantuan.db.dao.ConsumeLogDAO;
import com.fantuan.db.dao.FundLogDAO;
import com.fantuan.db.dao.GroupDAO;
import com.fantuan.db.dao.LoginKeyDAO;
import com.fantuan.db.dao.UserDAO;
import com.fantuan.db.dao.UserMoneyDAO;
import com.fantuan.db.service.FtService;

@Service
public class FtServiceImpl implements FtService{

	private static Log logger = LogFactory.getLog(FtServiceImpl.class);

	@Autowired
	@Qualifier("userDAO")
	private UserDAO userDAO;
	@Autowired
	@Qualifier("groupDAO")
	private GroupDAO groupDAO;	
	@Autowired
	@Qualifier("userMoneyDAO")
	private UserMoneyDAO userMoneyDAO;	
	@Autowired
	@Qualifier("consumeLogDAO")
	private ConsumeLogDAO consumeLogDAO;
	@Autowired
	@Qualifier("fundLogDAO")
	private FundLogDAO fundLogDAO;
	@Autowired
	@Qualifier("loginKeyDAO")
	private LoginKeyDAO loginKeyDAO;	
	
	/**
	 * 根据用户名和密码登录系统
	 * 成功返回对象
	 * 失败null
	 */
	public User login( String email, String password ) throws SQLException
	{
		logger.debug(StringUtils.repeat("*", 2) + "用户登录：" + email + "/"
				+ password);
		User user = null;
		user = userDAO.getUser(email, password);
		logger.debug(StringUtils.repeat("*", 2) + "用户登录结束：user=" + user);
		return user;
	}
	
	/**
	 * 新建饭团，user是建立人的用户信息
	 */
	public void createGroup( User user, Group group ) throws SQLException
	{
		logger.debug(StringUtils.repeat("*", 2) + "新建饭团：user=" + user + "/group="
				+ group);
		group.setnCreator(user.getnID());		
		long id = groupDAO.addGroup(group);		
		group.setnID( (int)id );
		logger.debug(StringUtils.repeat("*", 2) + "新建饭团结束：groupid=" + id);
	}
	
	
	/**
	 * true成功
	 * false已存在
	 */
	public boolean addUserToGroup( User user, Group group )throws SQLException
	{
		logger.debug(StringUtils.repeat("*", 2) + "饭团添加新成员：user=" + user + "/group="
				+ group);
		boolean retBool = false;
		
		//1.判断是否已经存在
		UserMoney userMoney = userMoneyDAO.getUserMoney(group.getnID(), user.getnID());
		if( userMoney == null )
		{
			userMoney = new UserMoney();
			userMoney.setdBalanceMoney(0.0);
			userMoney.setnConsumeTimes(0);
			userMoney.setnGroupID(group.getnID());
			userMoney.setnUserID(user.getnID());
			userMoney.setnState(UserMoney.STATE_OK);//正常状态
			userMoneyDAO.addUserMoney(userMoney);
			retBool = true;
		}
		
		//userMoneyDAO.addUserMoney(userMoney);		
		logger.debug(StringUtils.repeat("*", 2) + "饭团添加新成员完成");
		return retBool;
	}
	
	/**
	 * 退出饭团，目前仅更新标志位
	 */
	public boolean quitGroup( User user, Group group )throws SQLException
	{
		logger.debug(StringUtils.repeat("*", 2) + "饭团成员退出：user=" + user + "/group="
				+ group);
		
		boolean retBool = false;
		
		UserMoney userMoney = userMoneyDAO.getUserMoney(group.getnID(), user.getnID());
		if( userMoney != null )
		{
			userMoney.setnState(UserMoney.STATE_QUIT);
			userMoneyDAO.updateUserMoney(userMoney);
			retBool = true;
		}
		
		logger.debug(StringUtils.repeat("*", 2) + "饭团成员退出完成");
		
		return retBool;
	}
	
	
	/**
	 * 增加消费记录
	 */
	public boolean addConsume( Integer groupID, Integer consumeUserID, Integer[] memberUserIDs, double allMoney, String address, String remark, Date consumeDate )throws SQLException
	{
		//记录消费记录
		ConsumeLog consumeLog = new ConsumeLog();
		consumeLog.setdConsumeDate(consumeDate);
		consumeLog.setnConsumerCount(ArrayUtils.getLength(memberUserIDs));
		consumeLog.setnGroupID(groupID);
		consumeLog.setnMoney(allMoney);
		consumeLog.setnUserID(consumeUserID);
		consumeLog.setsAddress(address);
		consumeLog.setsRemark(remark);
		long nConsumeLogID = consumeLogDAO.addConsumeLog(consumeLog);
		
		//记录每个人的资金变动 //更新每个人的账户信息
		FundLog fundLog = new FundLog();//消费人信息
		fundLog.setdUpdateTime(new Date());
		fundLog.setnConsumeLogID((int)nConsumeLogID);
		fundLog.setnGroupID(groupID);
		fundLog.setnMoney(allMoney);
		fundLog.setnUserID(consumeUserID);
		fundLogDAO.addFundLog(fundLog);
		
		UserMoney userMoney = userMoneyDAO.getUserMoney(groupID, consumeUserID);
		userMoney.setdBalanceMoney(userMoney.getdBalanceMoney() + fundLog.getnMoney());
		userMoney.setdUpdateDate(new Date());
		userMoney.setnConsumeTimes(userMoney.getnConsumeTimes()+1);
		userMoneyDAO.updateUserMoney(userMoney);
		
		if( !ArrayUtils.isEmpty(memberUserIDs) )
		{
			for( Integer memberUserID:memberUserIDs )
			{
				fundLog = new FundLog();//消费人信息
				fundLog.setdUpdateTime(new Date());
				fundLog.setnConsumeLogID((int)nConsumeLogID);
				fundLog.setnGroupID(groupID);
				fundLog.setnMoney(-(double)(allMoney/ArrayUtils.getLength(memberUserIDs)));
				fundLog.setnUserID(memberUserID);
				fundLogDAO.addFundLog(fundLog);
				
				userMoney = userMoneyDAO.getUserMoney(groupID, memberUserID);
				userMoney.setdBalanceMoney(userMoney.getdBalanceMoney() + fundLog.getnMoney());
				userMoney.setdUpdateDate(new Date());
				if( memberUserID.intValue() != consumeUserID.intValue() )
				{
					userMoney.setnConsumeTimes(userMoney.getnConsumeTimes()+1);
				}
				userMoneyDAO.updateUserMoney(userMoney);
			}
		}
		
		//更新饭团的消费次数和消费金额
		Group group = groupDAO.getGroup(groupID);
		group.setnConsumeTimes(group.getnConsumeTimes()+1);
		group.setdConsumeSumMoney(group.getdConsumeSumMoney()+allMoney);
		group.setDupdateDate(consumeDate);		
		groupDAO.updateGroup(group);
		
		return true;
	}
	
	/**
	 * 删除消费记录
	 */
	public boolean removeConsume( Integer consumeID, Integer processUserID )throws SQLException
	{
		//1.删除消费日志
		ConsumeLog consumeLog = consumeLogDAO.getConsumeLog(consumeID);
		consumeLogDAO.removeConsumeLog(consumeID);		
		
		//2.删除个人消费日志
		fundLogDAO.removeFundLogs(consumeID);
		
		//3.更新个人记录
		//4.更新饭团消费次数和金额		
		//重建个人与群组消费数据
		groupDAO.updateGroupConsumeInfo(consumeLog.getnGroupID());
		
		//获取饭团全部成员，一一更新
		List<User> userList = userDAO.getUserListByGroupID(consumeLog.getnGroupID());
		for( User user:userList )
		{
			userMoneyDAO.updateUserMoney(consumeLog.getnGroupID(), user.getnID());
		}
		
		return true;
	}
}